<template>
  <div>
    <ElementDialog :visible.sync="show" top="5%" width="95%" title="整改措施">
      <FyCurd
        ref="crud"
        v-model="form"
        :page.sync="page"
        :data="tableData"
        :permission="permissionList"
        :table-loading="tableLoading"
        :option="tableOption"
        :before-open="handleOpenBefore"
        @selection-change="selectionChange"
        @on-load="getList"
        @search-change="searchChange"
        @refresh-change="refreshChange"
        @size-change="sizeChange"
        @current-change="currentChange"
        @row-update="handleUpdate"
        @row-save="handleSave"
        @row-del="handleDel">
        <template #menu="{ type, size, row }">
          <ElButton
            v-if="permissions.problem_rectify_add"
            :type="type"
            :size="size"
            icon="el-icon-edit"
            @click="addFeedBack(row)">
            整改反馈
          </ElButton>
        </template>
        <template #menuLeft>
          <ElButton
            v-if="permissions.problem_rectify_export"
            class="filter-item"
            plain
            type="primary"
            size="small"
            icon="el-icon-download"
            @click="exportExcel">
            导出
          </ElButton>
          <ElButton
            v-if="permissions.problem_rectify_export"
            class="filter-item"
            plain
            type="primary"
            size="small"
            icon="el-icon-upload"
            @click="$refs.excelUpload.show()">
            导入
          </ElButton>
          <ElButton
            v-if="permissions.problem_rectify_add"
            type="primary"
            size="small"
            icon="el-icon-edit"
            @click="timingReming()">
            定时提醒
          </ElButton>
        </template>
        <template #problemInforNum="scope">
          <ElTag style="cursor: pointer" @click="problemInforNumClick(scope.row)">{{
            scope.row.problemInforNum
          }}</ElTag>
        </template>
        <template #problemInforNumForm>
          <ElInput v-model="form.problemInforNum" :disabled="proInforNumDisplay" placeholder="选择问题单号" />
          <div>
            <ElTag v-show="form.problemInforNum" style="cursor: pointer" @click="showProblemInforDialog()">
              查看问题单
            </ElTag>
          </div>
        </template>
        <template #functionalNameForm="{ disabled }">
          <VueTreeSelect
            v-model="form.functionalOuid"
            :options="functionDeptOption"
            :normalizer="normalizer"
            :disabled="disabled"
            :show-count="true"
            placeholder="选择职能部门"
            @select="functionNameSelect" />
        </template>
        <template #timelimitTypeForm="{ disabled }">
          <ElSelect
            v-model="form.timelimitType"
            :disabled="disabled"
            placeholder="请选择完成时限"
            @change="timelimitTypeChange()">
            <ElOption key="0" label="长期" value="0" />
            <ElOption key="1" label="限期" value="1" />
            <ElOption key="2" label="立行立改" value="2" />
          </ElSelect>
        </template>
        <template #thoseResponsibleForm="{ type }">
          <RectifyDetailTable
            ref="rectifyDetailTable"
            :concurent-type="type"
            :rectify-id="form.id"
            :rectify-num="form.number" />
        </template>
        <template #thoseResponsible="scope">
          <ElTag v-for="item in scope.row.thoseResponsible ? scope.row.thoseResponsible.split(',') : ''" :key="item">{{
            item
          }}</ElTag>
        </template>
        <template #responsibilityDept="scope">
          <ElTag
            v-for="item in scope.row.responsibilityDept ? scope.row.responsibilityDept.split(',') : ''"
            :key="item">
            {{ item }}
          </ElTag>
        </template>
        <!-- 附件上传组件{ 需要传入uniqueCode/model/classify} -->
        <template #uploadPageForm>
          <UploadPage
            ref="UploadPage"
            :unique-code="form.unid"
            :upload-permissions="permissionList"
            :view-type="showType"
            model="problem"
            classify="rectify" />
        </template>
      </FyCurd>
      <template #footer>
        <span class="dialog-footer">
          <ElButton @click="show = false">关闭</ElButton>
        </span>
      </template>
      <ElementDialog :visible.sync="visibleFeedback" title="整改反馈" top="5%" width="95%">
        <FeedBack v-if="visibleFeedback" ref="feedBack" :rectify-id="rectifyId" :rectify-num="rectifyNum" />
        <template #footer>
          <span class="dialog-footer">
            <ElButton @click="visibleFeedback = false">关闭</ElButton>
            <!--        <el-button type="primary" @click="checkRowData" >确定</el-button>-->
          </span>
        </template>
      </ElementDialog>
    </ElementDialog>
    <!--excel 模板导入 -->
    <ExcelUpload
      ref="excelUpload"
      title="整改措施信息导入"
      :url="`${services.personnelService}/rectify/import`"
      :temp-url="`${services.personnelService}/sys-file/local/rectify.xlsx`"
      temp-name="整改措施信息导入模板.xlsx"
      @refreshDataList="refreshChange" />
    <ProblemInfo v-if="visibleProblemInfo" ref="proInfo" @getProblemInfoData="getProblemInfoData" />
    <SelectUser v-if="visibleSelectUser" ref="selectUser" :allow-choose-num="-1" @getUserData="getUserData" />
    <DlgMessageUserObjectForm
      ref="message"
      :visible.sync="showMessage"
      doc-code="Recitify"
      :form-disabled="false"
      source-type="ProblemRectify" />
    <InforModel ref="infor" :visible="false" />
  </div>
</template>

<script>
  import {
    putObj,
    delObj,
    getRegularlyRemind,
    getInforName,
    addAndRectifyDetailed,
    fetchThoseResponsibleList
  } from '@/api/problem/rectify'
  import { addRectifyDetaileds, getRectifyDetailedList, delRectifyDetailed } from '@/api/problem/rectifydetailed'
  import { getNumber } from '@/api/problem/infor'
  import { fetchTree } from '@/api/admin/dept'
  import { tableOption2 } from '@/const/crud/problem/rectify'
  import { mapState } from 'vuex'
  import { getUUID } from '@/api/admin/uuid'
  import RectifyDetailTable from './RectifyDetailTable'
  import FeedBack from '@/module/problem/feedback/index'
  import InforModel from '@/module/problem/infor/InforModel'
  import { services } from '@/config'

  export default {
    name: 'RectifyModel',
    components: {
      RectifyDetailTable,
      FeedBack,
      InforModel
    },
    props: {
      problemInforId: {
        type: Number,
        default: -1
      },
      problemInforNum: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        searchForm: {},
        tableData: [],
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 20 // 每页显示多少条
        },
        tableLoading: false,
        tableOption: tableOption2,
        form: {
          functionalOuid: 254
        },
        visibleProblemInfo: false,
        proInforNumDisplay: false,
        functionDeptOption: [],
        visibleResponsiPeople: false,
        visibleFeedback: false,
        rectifyId: -1,
        rectifyNum: '',
        dutyDeptData: [],
        visibleSelectUser: false,
        selectData: [],
        showMessage: false,
        sourceId: '',
        showType: '',
        show: false,
        services
      }
    },
    // eslint-disable-next-line vue/order-in-components
    computed: {
      ...mapState('user', ['permissions']),
      permissionList() {
        return {
          addBtn: this.$isEmpty(this.permissions.problem_rectify_add, false),
          delBtn: this.$isEmpty(this.permissions.problem_rectify_del, false),
          editBtn: this.$isEmpty(this.permissions.problem_rectify_edit, false),
          downloadBtn: this.$isEmpty(this.permissions.problem_rectify_download, false)
        }
      }
    },
    methods: {
      // 列表查询
      getList(page, params) {
        if (this.$isBlank(this.searchForm)) {
          this.searchForm = {}
        }
        if (this.problemInforId > 0) {
          this.searchForm.problemInforId = this.problemInforId
        }
        this.tableLoading = true
        fetchThoseResponsibleList(
          Object.assign(
            {
              current: page.currentPage,
              size: page.pageSize
            },
            params,
            this.searchForm
          )
        )
          .then(response => {
            this.tableData = response.data.data.records
            this.page.total = response.data.data.total
            this.tableLoading = false
          })
          .catch(() => {
            this.tableLoading = false
          })
      },
      // 删除
      handleDel: function (row, index) {
        this.$confirm(`是否确认删除ID为${row.id}`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            return delObj(row.id)
          })
          .then(data => {
            this.$message.success('删除成功')
            this.getList(this.page)
          })
      },
      // 更新
      handleUpdate: function (row, index, done, loading) {
        putObj(row)
          .then(data => {
            this.$message.success('修改成功')
            done()
            this.getList(this.page)
          })
          .catch(() => {
            loading()
          })
      },
      // 保存
      handleSave: function (row, done, loading) {
        this.$nextTick(() => {
          row.rectifyDetaileds = this.$refs.rectifyDetailTable.saveData
        })
        addAndRectifyDetailed(row)
          .then(data => {
            this.$message.success('添加成功')
            done()
            this.getList(this.page)
          })
          .catch(() => {
            loading()
          })
      },
      // 打开模态框之前
      handleOpenBefore(show, type) {
        window.boxType = type
        this.showType = type
        this.getdeptTreeSelect()
        if (this.problemInforId !== -1 && this.problemInforNum !== '') {
          this.form.problemInforId = this.problemInforId
          this.form.problemInforNum = this.problemInforNum
          this.proInforNumDisplay = true
        }
        // console.log(type)
        // 添加附件参数
        if (type === 'edit' || type === 'view') {
          this.$nextTick(() => {
            this.$refs.rectifyDetailTable.addResponsiPepople()
          })
        } else {
          this.form.functionalOuid = 254
          getUUID().then(response => {
            this.form.unid = response.data.data
          })
        }
        show()
      },
      // 每页条数改变事件
      sizeChange(pageSize) {
        this.page.pageSize = pageSize
      },
      // 当前页发生改变事件
      currentChange(current) {
        this.page.currentPage = current
      },
      // 查询事件
      searchChange(form, done) {
        this.searchForm = form
        this.page.currentPage = 1
        this.getList(this.page, form)
        done()
      },
      // 刷新事件
      refreshChange() {
        this.getList(this.page)
      },
      //  导出excel
      exportExcel() {
        const exportFileName = `整改措施_${this.$dateFormat(new Date())}.xlsx`
        this.$downBlobFile(`${services.personnelService}rectify/export`, this.searchForm, exportFileName)
      },
      // 打开问题信息模态框
      openProblemInfoDialog() {
        this.visibleProblemInfo = true
        this.$nextTick(() => {
          this.$refs.proInfo.init()
        })
      },
      // 获取选中问题信息数据
      getProblemInfoData(listInfo) {
        if (listInfo.length > 0) {
          this.form.problemInforNum = listInfo[0].number
          this.form.problemInforId = listInfo[0].id
        }
        // console.log(listInfo[0])
      },
      /** 查询菜单下拉树结构 */
      getdeptTreeSelect() {
        fetchTree().then(response => {
          this.functionDeptOption = response.data.data
        })
      },
      // 获取部门信息
      getDeptData(listDept) {
        if (listDept.length > 0) {
          this.form.functionalName = listDept[0].name
          this.form.functionalOuid = listDept[0].id
          this.form.functionalFullname = listDept[0].fullname
        }
      },
      timelimitTypeChange() {
        if (this.form.timelimitType === '0' || this.form.timelimitType === '2') {
          this.tableOption.column[9].display = false
          this.tableOption.column[8].display = false
        } else if (this.form.timelimitType === '1') {
          this.tableOption.column[9].display = true
          this.tableOption.column[8].display = true
        }
      },
      openAddDialog() {
        this.form.problemInforId = this.problemInforId
        this.form.problemInforNum = this.problemInforNum
        this.proInforNumDisplay = true
        this.tableOption.menuBar = false
        this.$refs.crud.rowAdd()
      },
      /** 转换菜单数据结构 */
      normalizer(node) {
        return {
          id: node.id,
          label: node.name,
          children: node.children
        }
      },
      /** 添加责任人 */
      addResponsiPepople(row) {
        this.rectifyId = parseInt(row.id)
        this.rectifyNum = row.number
        this.visibleResponsiPeople = true
        this.dutyDeptData = []
        const query = { rectifyId: row.id }
        getRectifyDetailedList(query).then(response => {
          this.dutyDeptData = response.data.data
        })
      },
      issuedTask(row) {},
      // 定时通知
      timingReming() {
        if (this.selectData.length === 0) {
          this.$message.warning('清先选择需要提示的整改单号')
          return
        }
        if (this.selectData.length > 1) {
          this.$message.warning('选择一条整改反馈')
          return
        }
        this.showMessage = true
        // 获取整改措施责任人
        getRegularlyRemind(this.selectData[0].id).then(res => {
          const rows = res.data.data
          if (rows.length > 0) {
            getInforName(this.selectData[0].id).then(res => {
              this.$refs.message.dataForm.subject = res.data.msg
            })
            this.sourceId = this.selectData[0].id
            // this.$refs.message.form.sourceId = this.selectData[0].id
            this.$refs.message.dataForm.timelimitType = this.selectData[0].timelimitType
            this.$refs.message.dataForm.startdate = this.selectData[0].startdate
            this.$refs.message.dataForm.enddate = this.selectData[0].enddate
            // console.log(this.$refs.message.dataForm)
            this.$refs.message.rows = rows
            this.$refs.message.init(this.sourceId)
          }
        })
      },
      addFeedBack(row) {
        this.rectifyId = parseInt(row.id)
        this.rectifyNum = row.number
        this.visibleFeedback = true
      },
      deleteDutyname(index, row) {
        if (row.id !== undefined) {
          delRectifyDetailed(row.id)
        }
        this.dutyDeptData.splice(index, 1)
      },
      // 获取选择的用户信息
      getUserData(userData) {
        for (let i = 0; i < userData.length; i++) {
          let isNotExist = true
          for (let j = 0; j < this.dutyDeptData.length; j++) {
            if (userData[i].userId === this.dutyDeptData[j].dutyUserid) {
              isNotExist = false
              break
            }
          }
          if (isNotExist) {
            const data = {}
            data.dutyName = userData[i].deptName
            data.dutyOuid = userData[i].deptId
            data.dutyFullname = userData[i].deptFullName
            data.dutyUserid = userData[i].userId
            data.dutyUsername = userData[i].realName
            this.dutyDeptData.push(data)
          }
        }
      },
      // 打开选择用户选择框
      openSelectUserDialog() {
        this.visibleSelectUser = true
        this.$nextTick(() => {
          this.$refs.selectUser.init()
        })
      },
      // 保存责任人
      saveDudyDept() {
        if (this.dutyDeptData.length > 0) {
          for (let i = 0; i < this.dutyDeptData.length; i++) {
            this.dutyDeptData[i].rectifyId = this.rectifyId
            this.dutyDeptData[i].rectifyNum = this.rectifyNum
          }
          addRectifyDetaileds(this.dutyDeptData)
            .then(data => {
              this.$message.success('添加成功')
              this.getList(this.page)
            })
            .catch(() => {})
        }
      },
      selectionChange(list) {
        this.selectData = list
      },
      functionNameSelect(node, instanceId) {
        this.form.functionalOuid = node.id
        this.form.functionalName = node.name
      },
      showProblemInforDialog() {
        getNumber(this.form.problemInforNum).then(response => {
          this.$refs.infor.$refs.crud.rowView(response.data.data)
        })
      },
      problemInforNumClick(row) {
        this.showType = 'view'
        getNumber(row.problemInforNum).then(response => {
          this.$refs.infor.$refs.crud.rowView(response.data.data)
        })
      },
      open() {
        this.getList(this.page)
        this.show = true
      },
      close() {
        this.show = false
      }
    }
  }
</script>
